package com.douding.server.service;

import com.douding.server.domain.Section;
import com.douding.server.domain.SectionExample;
import com.douding.server.dto.SectionDto;
import com.douding.server.dto.SectionPageDto;
import com.douding.server.mapper.SectionMapper;
import com.douding.server.util.CopyUtil;
import com.douding.server.util.UuidUtil;
import com.douding.server.util.ValidatorUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Service
public class SectionService {

    @Resource
    private SectionMapper sectionMapper;


    /**
     * 列表查询
     */
    public void list(SectionPageDto sectionPageDto) {
        PageHelper.startPage(sectionPageDto.getPage(), sectionPageDto.getSize());
        SectionExample example = new SectionExample();
        example.setOrderByClause("sort asc");
        example.createCriteria().
                andCourseIdEqualTo(sectionPageDto.getCourseId()).
                andChapterIdEqualTo(sectionPageDto.getChapterId());
        List<Section> sections = sectionMapper.selectByExample(example);
        PageInfo<Section> pageInfo = new PageInfo<>(sections);
        sectionPageDto.setTotal(pageInfo.getTotal());
        List<SectionDto> sectionDtos = CopyUtil.copyList(sections, SectionDto.class);
        sectionPageDto.setList(sectionDtos);
    }


    public void save(SectionDto sectionDto) {
        String id = sectionDto.getId();
        Section section = CopyUtil.copy(sectionDto, Section.class);
        if (!StringUtils.isEmpty(id)) {
            update(section);
            return;
        }
        insert(section);
    }

    //新增数据
    private void insert(Section section) {
        ValidatorUtil.require(section.getTitle(), "标题", String.class);
        ValidatorUtil.require(section.getSort(), "标题", Integer.class);
        section.setId(UuidUtil.getShortUuid());
        section.setCreatedAt(new Date());
        sectionMapper.insert(section);
    }

    //更新数据
    private void update(Section section) {
        SectionExample sectionExample = new SectionExample();
        sectionExample.createCriteria().andIdEqualTo(section.getId());
        section.setUpdatedAt(new Date());
        sectionMapper.updateByExample(section, sectionExample);
    }

    public void delete(String id) {
        sectionMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询某一课程下的所有节
     */
    public List<SectionDto> listByCourse(String courseId) {
        SectionExample example = new SectionExample();
        example.createCriteria().andCourseIdEqualTo(courseId);
        List<Section> sections = sectionMapper.selectByExample(example);
        return CopyUtil.copyList(sections, SectionDto.class);
    }

}//end class
